package com.blockchain.console.servlets.user;

import java.math.BigDecimal;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.blockchain.console.service.system.ConstantManage;
import com.blockchain.console.service.user.UserManage;
import com.blockchain.framework.config.entity.VariableBean;
import com.blockchain.framework.config.service.VariableManage;
import com.blockchain.framework.resource.PromptLevel;
import com.blockchain.framework.service.ServiceSession;
import com.blockchain.util.parser.IntegerParser;

public class FinanceEditer extends AbstractUserServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void processGet(HttpServletRequest request,
			HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		String userid = request.getParameter("userid");
		sendRedirect(request, response, 
				getController().getURI(request, FinanceEdit.class) + "?userid=" + userid);
	}
	
	@Override
	protected void processPost(HttpServletRequest request, HttpServletResponse response, ServiceSession serviceSession)
			throws Throwable {
		if (serviceSession.getSession().getAccountId() != 1) {
			return;
		}
		
		UserManage usermanager = serviceSession.getService(UserManage.class);
		String userid = request.getParameter("userid");
		int bid = IntegerParser.parse(request.getParameter("bid"));
		if (userid.equals("otc")) {
			VariableManage variableManage = serviceSession
					.getService(VariableManage.class);
			ConstantManage constantManage = serviceSession
					.getService(ConstantManage.class);
			String key = "SYSTEM.ISOPEN";
			VariableBean variableBean = variableManage.get(key);
			String value = bid==1? "KFOTC" : "GBOTC";
			try {
				variableManage.setProperty(key, value);
				constantManage.addConstantLog(key, variableBean.getDescription(),
						variableBean.getValue(), value);
				
			} catch (Throwable t) {
				getController().prompt(request, response, PromptLevel.WARRING,
						t.getMessage());
				processGet(request, response, serviceSession);
			}
		} else {
		
			String sl = (String)request.getParameter("sl");
			BigDecimal num = new BigDecimal(sl);
			if (num.compareTo(BigDecimal.ZERO) < 0) {
				return;
			}
			
			if (bid == 0) {
				usermanager.editUserRmb(userid, num);
			}
			if (bid > 0) {
				usermanager.editUserXlb(userid, bid, num);
			}
	
	
			sendRedirect(request, response, 
					getController().getURI(request, FinanceEdit.class) + "?userid=" + userid);
		}
	}
	
}
